<?
include_once 'CoreModel.php';
Class ImportMaterialModel extends CoreModel {
	private $table;
	public function __construct() {
		$this -> table = "material_data";
		parent::__construct();
	}

	public function insertConnectData($result) {
		/* $result is result from sap */
		//	print_r($result);
		//exit();
		// default log message
		$data_log['log_function'] = "ZSDRFC_MATERIAL_DATA";
		$data_log['log_table'] = "MATERIAL_DATA";
		$data_log['log_record'] = 0;
		$data_log['log_type'] = "INSERT";
		$data_log['log_status'] = "COMPLETED";
		$data_log['log_by_name'] = "Batch Job";
		$data_log['log_page'] = "adminpanel/importmaterial";

		$numRows = 0;
		// start begin trans
		$this -> db -> trans_begin();
		$this -> db -> query('delete from MATERIAL_DATA');
		$this->db->query("SET NAMES tis620"); 
		$dataInsert = array();
		
		foreach ($result["MATERIAL_DATA"] as $mat) {
			$data = array();
			$data['MATNR'] = $mat["MATNR"];
			$data['MAKTX'] = $mat["MAKTX"];
			$data['MATGRP'] = $mat["MATGRP"];
			$data['MAIN_GROUP'] = $mat["MAIN_GROUP"];
			$data['MGROUP'] = $mat["GROUP"];
			$data['SUB_GROUP'] = $mat["SUB_GROUP"];
			$data['BASE_UNIT'] = $mat["BASE_UNIT"];
			$data['EA_PACK'] = $mat["EA_PACK"];
			$data['EA_CARTON'] = $mat["EA_CARTON"];
			$data['STOCK'] = $mat["STOCK"];
			$data['CREDIT_VAT_PRICE'] = $this->convertValue($mat["CREDIT_VAT_PRICE"]);
			$data['CREDIT_VAT_UNIT'] = $mat["CREDIT_VAT_UNIT"];
			$data['CREDIT_NOVAT_PRICE'] = $this->convertValue($mat["CREDIT_NOVAT_PRICE"]);
			$data['CREDIT_NOVAT_UNIT'] = $mat["CREDIT_NOVAT_UNIT"];
			$data['VAN_VAT_PRICE'] = $this->convertValue($mat["VAN_VAT_PRICE"]);
			$data['VAN_VAT_UNIT'] = $mat["VAN_VAT_UNIT"];
			$data['VAN_NOVAT_PRICE'] = $this->convertValue($mat["VAN_NOVAT_PRICE"]);
			$data['VAN_NOVAT_UNIT'] = $mat["VAN_NOVAT_UNIT"];
			$dataInsert[] = $data;
		}

		// insert into SALES_DATA;
		$this -> db -> insert_batch($this -> table, $dataInsert);

		if ($this -> db -> trans_status() === FALSE) {
			// if error on tranaction
			$this -> db -> trans_rollback();
				
			// insert log  table & page
			$this->insertLogFailed('ZSDRFC_MATERIAL_DATA', 'MATERIAL_DATA', 'adminpanel/importmaterial');
			
			return array("flag" => false, "message" => "error on transfer");
		} else {
			// when complete
			$this -> db -> trans_commit();
			$this->insertLogComplete('ZSDRFC_MATERIAL_DATA', 'MATERIAL_DATA', count($dataInsert), 'adminpanel/importmaterial');
			return array("flag" => true, "connect_row" => count($dataInsert));
		}
	}

}
?>